#include "../source/server.hpp"

void OnMessage(const PtrConnection &conn, Buffer *buffer)
{
    DBG_LOG("RECV: %s", buffer->ReadPosition());
    buffer->MoveReadOffset(buffer->ReadAbleSize());
    const std::string str = "Hello World!";
    conn->Send(str.c_str(), str.size());
    // conn->Shutdown();
}

// 管理的所有连接
std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
EventLoop base_loop;
LoopThreadPool *loop_pool;
void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("NEW CONNECTION: %p", conn.get());
}
// 获取新连接，为新连接创建一个Channel并且添加监控
void NewConnection(int fd)
{
    ++conn_id;
    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, fd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10); // 启动非活跃销毁
    conn->Established();             // 就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("NEW CONNECTION-----------------");
}
int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    Acceptor acceptor(&base_loop, 8080);
    // 为监听套接字，创建一个Channel进行事件管理以及事件处理
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();

    base_loop.Start();
    return 0;
}